package com.mooral.web.action.voucher;

import java.sql.ResultSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import com.mooral.bean.Bean;
import com.mooral.bean.Categories;
import com.mooral.bean.Category;
import com.mooral.bean.Merchant;
import com.mooral.bean.Merchants;
import com.mooral.bean.Vouchers;
import com.mooral.context.Context;
import com.mooral.web.action.MooralAction;
import com.mooral.web.util.SorterUtils;

public class SearchByCategoryAction extends MooralAction {

 	public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, Context context) throws Exception {

		  DynaActionForm dform = (DynaActionForm) form;
		  String query = (String)dform.get("query");
		  
		  
			int pageSelected = 1;
			if(request.getParameter("pageSelected")!= null){
				try{
					pageSelected = Integer.parseInt( request.getParameter("pageSelected") );
				}catch(NumberFormatException e){
					pageSelected = new Integer(1);
				}
			}		  
		  
		  // TODO TOMAR IDS DE LAS CATEGORIEAS
			Categories categories = new Categories();
			categories.populate("SELECT id, parent_id as parentId, name, image, slug  FROM categories");
			categories = (new SorterUtils()).arrangeCategoriesByDependency(categories);
			Category category = categories.getBySlug(query);
			
			if(category == null){
				request.setAttribute("listSize", 0);
				request.setAttribute("actionSearch", mapping.getPath());
				request.setAttribute("query", query);
				request.setAttribute("pageSelected", new Integer(pageSelected));
			  
				return mapping.findForward(ACTION_SUCCESS);
			}
			
			
			Collection ids = new Vector(category.getChildsIds());
			ids.add(category.get("id"));
			String strIds = "";
			Iterator iterator = ids.iterator();
			while(iterator.hasNext()){
				strIds += iterator.next().toString() + ",";
			}
			strIds = strIds.substring(0,strIds.length() - 1);
			
			
			Vouchers vouchers = new Vouchers();

			String sql = "select 	* " +
			  		"  			from 		vouchers " +
			  		"			where 		category_id in ( " + strIds + " )" +
			  		"			limit " + (pageSelected - 1) * Context.PAGE_SIZE + ", " + Context.PAGE_SIZE;
			vouchers.populate( sql);

			request.setAttribute("vouchers", vouchers);
		  

			// Paginacion
			request.setAttribute("listSize", vouchers.getCount(sql));
			request.setAttribute("actionSearch", mapping.getPath());
			request.setAttribute("query", query);
			request.setAttribute("pageSelected", new Integer(pageSelected));
		  
			return mapping.findForward(ACTION_SUCCESS);
	}
	
}
